package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.MapLocationListAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

public class PublishLocationMapActivity extends Activity implements PoiSearch.OnPoiSearchListener, OnClickListener {
    private RecyclerView rv_map_location;
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private int currentPage = 1;
    private PoiSearch.Query query;
    private PoiResult poiResult;
    private MapLocationListAdapter adapter;
    private List<PoiItem> poiItemslist = new ArrayList<>();
    private TextView headtvCity;
    private ProgressDialog mProgressDialog;
    private boolean isBottom;
    private String ll;
    private String text_content = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_plmap);
        registerBroadcastReceiver();
        ll = getIntent().getStringExtra("ll");
        initView();
        initLocation();
    }

    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionUpdateFromText);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionUpdateFromText:
                    if (intent != null) {
                        String fromtx = intent.getStringExtra("tx");
                        text_content = fromtx;
                        sendBroadcast(new Intent(ACTIONs.actionUpdateLocation).putExtra("location", text_content));
                        finish();
                    }
                    break;
            }
        }
    };

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mAMapLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(false);
        mLocationOption.setHttpTimeOut(20000);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.plmap_back:
                finish();
                break;
            case R.id.location_creat:
                Intent intent = new Intent(PublishLocationMapActivity.this, TimeCardFromActivity.class);
                intent.putExtra("text_content", text_content);
                startActivity(intent);
                break;
            case R.id.location_noshow:
                sendBroadcast(new Intent(ACTIONs.actionUpdateLocation).putExtra("location", "不显示位置"));
                finish();
                break;
            case R.id.location_citycode:
                sendBroadcast(new Intent(ACTIONs.actionUpdateLocation).putExtra("location", pamapLocation.getCity()));
                finish();
                break;
        }
    }

    private void initView() {
        findViewById(R.id.plmap_back).setOnClickListener(this);
        rv_map_location = (RecyclerView) findViewById(R.id.rv_map_location);
        rv_map_location.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rv_map_location.setItemAnimator(new DefaultItemAnimator());
        adapter = new MapLocationListAdapter(this, poiItemslist, ll,false);
//        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(adapter);
        rv_map_location.setAdapter(adapter);
        View header = LayoutInflater.from(this).inflate(R.layout.maplocation_header, rv_map_location, false);
        adapter.setHeaderView(header);
        header.findViewById(R.id.location_creat).setOnClickListener(this);
        header.findViewById(R.id.location_noshow).setOnClickListener(this);
        headtvCity = (TextView) header.findViewById(R.id.location_citycode);
        headtvCity.setOnClickListener(this);
        rv_map_location.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                // 已经到底，返回
                if (isBottom) {
                    return;
                }
                // 加载中，返回
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_map_location);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                // 加载下一页
                RecyclerViewStateUtils.setFooterViewState(PublishLocationMapActivity.this, rv_map_location, 10, LoadingFooter.State.Loading, null);
                rv_map_location.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (pamapLocation != null) {
                            query = new PoiSearch.Query("", "", CityCode);
                            query.setPageSize(10);
                            query.setPageNum(currentPage);// 设置查第一页
                            currentPage++;
                            poiSearch = new PoiSearch(PublishLocationMapActivity.this, query);
                            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(pamapLocation
                                    .getLatitude(), pamapLocation.getLongitude()), 1000));
                            poiSearch.setOnPoiSearchListener(PublishLocationMapActivity.this);
                            poiSearch.searchPOIAsyn();
                        }
                    }
                }, 500);
            }
        });

    }


    @Override
    protected void onPause() {
        super.onPause();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            // 搜索POI的结果
            if (result != null && result.getQuery() != null) {
                mProgressDialog.dismiss();
                // 是否是同一条
                if (result.getQuery().equals(query)) {
                    poiResult = result;
                    final int resultPages = poiResult.getPageCount();
                    final List<PoiItem> poiItems = poiResult.getPois();
                    Log.i("xjs", "poiItems.sssize==>" + poiItems.size());
                    if (poiItems != null && poiItems.size() > 0) {
                        poiItemslist.addAll(poiItems);
                        adapter.notifyDataSetChanged();
                        if (poiItems.size() == 0) {
                            isBottom = true;
                            RecyclerViewStateUtils.setFooterViewState(this, rv_map_location, 10, LoadingFooter.State.TheEnd, null);
                        } else {
                            RecyclerViewStateUtils.setFooterViewState(rv_map_location, LoadingFooter.State.Normal);
                        }
                    }
                }
            }
        } else {
            Log.i("xjs", "rcode==>" + rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem result, int code) {
        // Log.i("xjs", "地址：" + result.getSnippet());
    }

    PoiSearch poiSearch;
    String CityCode;
    AMapLocation pamapLocation;
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    pamapLocation = amapLocation;
                    String address = amapLocation.getAddress();
                    String city = amapLocation.getCity();
                    String Street = amapLocation.getStreet() + amapLocation.getStreetNum();//街道信息
                    CityCode = amapLocation.getCityCode();
//                    Log.i("xjs", "address==>" + address);
//                    Log.i("xjs", "city==>" + city);
//                    Log.i("xjs", "Street==>" + Street);
//                    Log.i("xjs", "CityCode==>" + CityCode);
                    headtvCity.setText(city);
                    query = new PoiSearch.Query("", "", CityCode);
                    query.setPageSize(10);
                    query.setPageNum(0);// 设置查第一页
                    mProgressDialog.dismiss();
                    poiSearch = new PoiSearch(PublishLocationMapActivity.this, query);
                    poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(amapLocation
                            .getLatitude(), amapLocation.getLongitude()), 1000));
                    poiSearch.setOnPoiSearchListener(PublishLocationMapActivity.this);
                    poiSearch.searchPOIAsyn();
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    Toast.makeText(PublishLocationMapActivity.this, "定位失败!", Toast.LENGTH_SHORT).show();
                    mProgressDialog.dismiss();
                }
            } else {
                Toast.makeText(PublishLocationMapActivity.this, "定位失败!", Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        }
    };
}
